package com.sdr.takepicplugin;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class TakePicUploadActivity extends AppCompatActivity implements FileUploadManger.OnUploadListener {
    //0 上传闸站图片信息  1 值班记录信息 2 采购单 3 入库单 4 出库单
    private int status = 0;
    private LinearLayout layoutDes;
    private LinearLayout layoutTime;
    private EditText edDes;
    private Button btnTime;
    private Button btnUpload;
    private NoScrollGridView gvPhotos;
    private gridAdapter adapter;
    private Map<Uri, Bitmap> cache = new HashMap<Uri, Bitmap>();
    private int screenWidth;
    private int lpWidth;
    private SimpleDateFormat smp;
    private ProgressDialog pd;
    private String serverUri;
    private String userId;
    private String accessToken;
    private LinearLayout layoutPeople;
    private EditText edPeople;
    private ActionBar actionBar;
    private Button btnAudio;
    private static final int CAMERA_RESULT = 0x01;
    public static int RECORD_REQUEST = 0x02;
    private UploadFile audioUploadFile;
    private String title;

    private static final String timeKey = "time";
    private static final String userIdKey = "userId";
    private static final String accessTokenKey = "accessToken";
    private static final String statusKey = "status";
    private static final String idKey = "id";
    private static final String serverIPKey = "serverUri";
    private static final String titleKey = "title";

    private Button btnAudioEdit;
    private RelativeLayout layoutAudio;
    private boolean canSet;
    private Uri cacheUri;
    public Uri currentUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getResources().getIdentifier("take_pic_upload", "layout", getPackageName()));
        initView();
    }

    private void initView() {
        String temp = getIntent().getStringExtra(statusKey);
        if (TextUtils.isEmpty(temp)) {
            status = 0;
        } else {
            status = Integer.parseInt(temp);
        }
        accessToken = getIntent().getStringExtra(accessTokenKey);
        userId = getIntent().getStringExtra(userIdKey);
        serverUri = getIntent().getStringExtra(serverIPKey);
        title = getIntent().getStringExtra(titleKey);


        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        if (actionBar != null && TextUtils.isEmpty(title)) {
            actionBar.setTitle(title);
        }
//        userId = "43";
//        accessToken = "787a088645354f58855ef495ddb6fe72";
//        serverUri = "http://58.240.174.254:8090/xitang-rest/upload/uploadStationData";

        //获取手机屏幕的宽高
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 屏幕宽度（像素）
        screenWidth = metric.widthPixels;
        final float scale = getResources().getDisplayMetrics().density;
        lpWidth = (screenWidth - (int) (15 * scale + 0.5f)) / 3;

        layoutDes = (LinearLayout) findViewById(getResources()
                .getIdentifier("layoutDes", "id", getPackageName()));
        layoutTime = (LinearLayout) findViewById(getResources()
                .getIdentifier("layoutTime", "id", getPackageName()));
        layoutPeople = (LinearLayout) findViewById(getResources()
                .getIdentifier("layout_people", "id", getPackageName()));
        layoutAudio = (RelativeLayout) findViewById(getResources()
                .getIdentifier("layout_audio", "id", getPackageName()));


        edDes = (EditText) findViewById(getResources()
                .getIdentifier("ed_Des", "id", getPackageName()));
        edPeople = (EditText) findViewById(getResources()
                .getIdentifier("et_people", "id", getPackageName()));
        btnTime = (Button) findViewById(getResources()
                .getIdentifier("btn_time", "id", getPackageName()));
        btnUpload = (Button) findViewById(getResources()
                .getIdentifier("btn_upload", "id", getPackageName()));
        gvPhotos = (NoScrollGridView) findViewById(getResources()
                .getIdentifier("gv_photos", "id", getPackageName()));
        btnAudio = (Button) findViewById(getResources()
                .getIdentifier("btn_audio", "id", getPackageName()));
        btnAudioEdit = (Button) findViewById(getResources()
                .getIdentifier("btn_audio_add_del", "id", getPackageName()));

        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(accessToken)
                || TextUtils.isEmpty(serverUri)) {
            Toast.makeText(this, "必要信息缺失", Toast.LENGTH_SHORT).show();
            btnUpload.setClickable(false);
        }

        switch (status) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                break;
            case 6:
                break;
            case 7:
                break;
            default:
                break;
        }

        adapter = new gridAdapter();
        gvPhotos.setAdapter(adapter);

        smp = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.CHINA);

        btnTime.setText(smp.format(new Date()));

        btnTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choiceDate();
            }
        });
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitResult();
            }
        });
        btnAudioEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String temp = btnAudioEdit.getText().toString();
                if (!TextUtils.isEmpty(temp) && temp.equals("添加")) {
                    Intent intent = new Intent(
                            MediaStore.Audio.Media.RECORD_SOUND_ACTION);
                    startActivityForResult(intent, RECORD_REQUEST);
                    return;
                }
                if (!TextUtils.isEmpty(temp) && temp.equals("删除")) {
                    audioUploadFile = null;
                    btnAudio.setText("");
                    btnAudioEdit.setText("添加");
                    return;
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == CAMERA_RESULT) {
//            adapter.addItem();
            InputStream fs = null;
            FileOutputStream fos = null;
            InputStream fsTemp = null;
            File file = null;
            try {
                fs = getContentResolver().openInputStream(currentUri);
                file = new File(getExternalCacheDir(), String.valueOf(System.currentTimeMillis()));
                fos = new FileOutputStream(file);
                fsTemp = getContentResolver().openInputStream(currentUri);

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(fs, null, options);
                fs.close();
                options.inJustDecodeBounds = false;

                int h = options.outHeight;
                int w = options.outWidth;

                float hh = 1920f;//
                float ww = 1920f;//

                // 最长宽度或高度1024
                float be = 1.0f;
                if (w > h && w > ww) {
                    be = (float) (w / ww);
                } else if (w < h && h > hh) {
                    be = (float) (h / hh);
                }
                if (be <= 0) {
                    be = 1.0f;
                }
                options.inSampleSize = (int) be;

                Bitmap temp = BitmapFactory.decodeStream(fsTemp, null, options);
                temp.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                if (!temp.isRecycled())
                    temp.recycle();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fs != null) {
                        fs.close();
                    }
                    if (fsTemp != null) {
                        fsTemp.close();
                    }
                    if (fos != null) {
                        fos.flush();
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            cacheUri = Uri.fromFile(file);
            adapter.addItem();
        }
        if (requestCode == RECORD_REQUEST) {
            if (audioUploadFile == null)
                audioUploadFile = new UploadFile();
            if (TextUtils.isEmpty(data.getType())) {
                audioUploadFile.setType("audio/AMR");
            } else {
                audioUploadFile.setType(data.getType());
            }
            audioUploadFile.setUri(data.getData());
            String uriString = audioUploadFile.getUri().getPath();
            String fileName = uriString.substring(uriString.lastIndexOf("/") + 1);
            if (!fileName.toLowerCase().contains(".amr")) {
                fileName += ".amr";
            }
            btnAudio.setText(fileName);
            btnAudioEdit.setText("删除");
            return;
        }
    }

    public void commitResult() {
        String des = edDes.getText().toString();
        String time = btnTime.getText().toString();
        String people = edPeople.getText().toString();
        if (adapter.getCount() < 2) {
            Toast.makeText(this, "请添加图片", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (status) {
            case 0: {
                if (TextUtils.isEmpty(des)) {
                    Toast.makeText(this, "请添加描述信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, String> temp = new HashMap<String, String>();
                temp.put("des", des);
                temp.put("userId", userId);
                temp.put("accessToken", accessToken);
                uploadData(temp);
            }
            break;
            case 1: {
                if (TextUtils.isEmpty(time)) {
                    Toast.makeText(this, "请选择时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, String> temp = new HashMap<String, String>();
                temp.put("time", time);
                temp.put("accessToken", accessToken);
                temp.put("userId", userId);
                uploadData(temp);
            }
            break;
            case 2: {
                if (TextUtils.isEmpty(time)) {
                    Toast.makeText(this, "请选择时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(des)) {
                    Toast.makeText(this, "请添加描述信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(people)) {
                    Toast.makeText(this, "请填写人员信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, String> temp = new HashMap<String, String>();
                temp.put("time", time);
                temp.put("des", des);
                temp.put("people", people);
                temp.put("accessToken", accessToken);
                temp.put("userId", userId);
                uploadData(temp);
            }
            break;
            case 3: {
                if (TextUtils.isEmpty(time)) {
                    Toast.makeText(this, "请选择时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(des)) {
                    Toast.makeText(this, "请添加描述信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(people)) {
                    Toast.makeText(this, "请填写人员信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, String> temp = new HashMap<String, String>();
                temp.put("time", time);
                temp.put("des", des);
                temp.put("people", people);
                temp.put("accessToken", accessToken);
                temp.put("userId", userId);
                uploadData(temp);
            }
            break;
            case 4: {
                if (TextUtils.isEmpty(time)) {
                    Toast.makeText(this, "请选择时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(des)) {
                    Toast.makeText(this, "请添加描述信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(people)) {
                    Toast.makeText(this, "请填写人员信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, String> temp = new HashMap<String, String>();
                temp.put("time", time);
                temp.put("des", des);
                temp.put("people", people);
                temp.put("accessToken", accessToken);
                temp.put("userId", userId);
                uploadData(temp);
            }
            break;
            default:
                Toast.makeText(this, "未识别的类型", Toast.LENGTH_SHORT).show();

        }
    }

    public void uploadData(Map<String, String> params) {

        List<UploadFile> temp = new ArrayList<UploadFile>();

        for (int i = 0; i < adapter.getCount() - 1; i++) {
            temp.add(new UploadFile(adapter.getItem(i), "image/jpeg"));
        }
        if (audioUploadFile != null) {
            temp.add(audioUploadFile);
        }
        FileUploadManger manger = new FileUploadManger(this);
        manger.setUploadListener(this);
        manger.upload(serverUri, params, temp);
        pd = new ProgressDialog(this);
        pd.setMessage("上传中，请稍等...");
        pd.setCancelable(false);
        pd.show();
    }


    private void choiceDate() {
        canSet = true;
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dpDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                if (canSet) {
                    choiceTime(year, monthOfYear, dayOfMonth);
                    canSet = false;
                }
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dpDialog.show();
    }

    private void choiceTime(final int year, final int monthOfYear, final int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        TimePickerDialog tpDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                GregorianCalendar gregorianCalendar = new GregorianCalendar(year, monthOfYear, dayOfMonth, hourOfDay, minute);
                btnTime.setText(smp.format(gregorianCalendar.getTime()));
            }
        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
        tpDialog.show();
    }

    @Override
    public void onResult(JSONObject resJson) {
        if (pd.isShowing()) {
            pd.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        if (resJson == null) {
            builder.setMessage("上传失败");
        } else {
            int code = 0;
            String msg = null;
            try {
                code = resJson.getInt("code");
                msg = resJson.getString("msg");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (code == 200) {
                for (Uri uri : adapter.getList()) {
                    File temp = new File(uri.getPath());
                    if (temp.exists() && temp.isFile())
                        temp.delete();
                }

                edDes.setText(null);
                adapter.dataList = new ArrayList<Uri>();
                adapter.notifyDataSetChanged();
                builder.setMessage("上传成功");
            } else {
                if (msg != null) {
                    builder.setMessage("上传失败：\n" + msg);
                } else {
                    builder.setMessage("上传失败");
                }
            }
        }
        builder.setPositiveButton("确定", null);
        builder.show();
    }

    class gridAdapter extends BaseAdapter {

        private List<Uri> dataList = new ArrayList<Uri>();

        gridAdapter() {
            Resources r = getResources();
            int resId = r.getIdentifier("btn_add_images_upload", "drawable", getPackageName());
            String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                    + r.getResourcePackageName(resId) + "/"
                    + r.getResourceTypeName(resId) + "/"
                    + r.getResourceEntryName(resId);
            this.dataList.add(Uri.parse(uriString));
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Uri getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void addItem() {
            dataList.add(dataList.size() - 1, cacheUri);
            notifyDataSetChanged();
        }

        public List<Uri> getList() {
            return dataList;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final Uri uri = dataList.get(position);
            viewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(TakePicUploadActivity.this).inflate(getResources().getIdentifier("item_image", "layout", getPackageName()), parent, false);
//                convertView.setLayoutParams(new ViewGroup.LayoutParams(lpWidth, lpWidth));
                ViewGroup.LayoutParams p = convertView.getLayoutParams();
                p.height = lpWidth;
                holder = new viewHolder();

                holder.pic = (ImageView) convertView.findViewById(getResources()
                        .getIdentifier("iv_photo", "id", getPackageName()));
                holder.del_img = (ImageView) convertView.findViewById(getResources()
                        .getIdentifier("iv_delete", "id", getPackageName()));
                convertView.setTag(holder);
            } else {
                holder = (viewHolder) convertView.getTag();
            }


            if (position == dataList.size() - 1) {
                holder.pic.setImageURI(uri);
                holder.del_img.setVisibility(View.GONE);
                holder.pic.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        takePic();
                    }
                });
            } else {
                Bitmap bmp = cache.get(uri);
                if (bmp == null) {
                    try {
                        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
                        bmpFactoryOptions.inJustDecodeBounds = true;
                        bmp = BitmapFactory
                                .decodeStream(getContentResolver().openInputStream(
                                        uri), null, bmpFactoryOptions);

                        int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
                                / (float) 200);
                        int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
                                / (float) 200);
                        if (heightRatio > 1 && widthRatio > 1) {
                            if (heightRatio > widthRatio) {
                                // Height ratio is larger, scale according to it
                                bmpFactoryOptions.inSampleSize = heightRatio;
                            } else {
                                // Width ratio is larger, scale according to it
                                bmpFactoryOptions.inSampleSize = widthRatio;
                            }
                        }

                        // Decode it for real
                        bmpFactoryOptions.inJustDecodeBounds = false;
                        bmp = BitmapFactory
                                .decodeStream(getContentResolver().openInputStream(
                                        uri), null, bmpFactoryOptions);
                        cache.put(uri, bmp);
                        holder.pic.setImageBitmap(bmp);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    holder.pic.setImageBitmap(bmp);
                }

                holder.del_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        File tempFile = new File(dataList.get(position).getPath());
                        if (tempFile.exists() && tempFile.isFile())
                            tempFile.delete();

                        dataList.remove(position);
                        adapter.notifyDataSetChanged();
                        Uri temp = dataList.get(position);
                        Bitmap tempBitmap = cache.get(temp);
                        if (tempBitmap != null) {
                            cache.remove(temp);
                            if (!tempBitmap.isRecycled()) {
                                tempBitmap.recycle();
                            }
                        }
                    }
                });
                holder.pic.setOnClickListener(null);
                if (holder.del_img.getVisibility() != View.VISIBLE) {
                    holder.del_img.setVisibility(View.VISIBLE);
                }
            }
            return convertView;
        }

        class viewHolder {
            private ImageView pic;
            private ImageView del_img;
        }
    }

    private void intentTakePicture() {
        currentUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, currentUri);
        startActivityForResult(intent, CAMERA_RESULT);
    }

    private void takePic() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            }, 111);
        } else {
            intentTakePicture();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 111 && grantResults.length == 3) {
            intentTakePicture();
        }
    }
}
